package pers.zxk.jlytnews.servlet;

import net.sf.json.JSONArray;
import pers.zxk.jlytnews.base.BaseServlet;
import pers.zxk.jlytnews.dao.FoodTypeDao;
import pers.zxk.jlytnews.dao.impl.FoodTypeDaoImpl;
import pers.zxk.jlytnews.entity.FoodType;
import pers.zxk.jlytnews.manager.UserStateManager;
import pers.zxk.jlytnews.util.CommonUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.List;

public class FoodTypeServlet extends HttpServlet {
    private FoodTypeDao mFoodTypeDao = new FoodTypeDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取能够与“url-pattern”中匹配的路径
        String method = req.getServletPath();

        //(此时处理的请求是查询 query.do)
        System.out.println("request.getServletPath()获取的值为: " + method);//输出 /query.do

        //2.通过字符串截取，把方法名 query 截取出来
        int i = method.lastIndexOf("/");
        method = method.substring(i + 1, method.length());

        System.out.println("截取后的值为： " + method);

        Method m = null;
        try {
            //3.获取当前类中名字为 method 的方法
            m = this.getClass().getDeclaredMethod(method,
                    HttpServletRequest.class, HttpServletResponse.class);

            //4.调用 method 方法
            m.setAccessible(true);
            m.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addFoodType(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        //判断用户权限
        if(!UserStateManager.isAdmin(req)){
            CommonUtil.sendJsonData(resp, null, 1, "无权操作！");
            return;
        }

        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String name = req.getParameter("name");
        String remarks = req.getParameter("remarks");

        //todo 检查名称他是否已经存在

        if(name==null){
            CommonUtil.sendJsonData(resp, "添加失败", 1, "名称不能为空！");
            return;
        }

        //更新数据并向客户端返回消息
        try {
            if (mFoodTypeDao.addFoodType(name, remarks)) {
                CommonUtil.sendJsonData(resp, "添加成功", 0, "");
            } else {
                CommonUtil.sendJsonData(resp, "添加失败", 1, "");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, "添加失败", 1, exception.getMessage());
        }
    }

    public void delFoodType(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //判断用户权限
        if(!UserStateManager.isAdmin(req)){
            CommonUtil.sendJsonData(resp, null, 1, "无权操作！");
            return;
        }

        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String id = req.getParameter("id");

        //更新数据并向客户端返回消息
        try {
            if (mFoodTypeDao.delFoodType(Integer.parseInt(id))) {
                CommonUtil.sendJsonData(resp, "删除成功", 0, "");
            } else {
                CommonUtil.sendJsonData(resp, "删除失败", 1, "");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, "删除失败", 1, exception.getMessage());
        }
    }

    public void updateFoodType(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        //判断用户权限
        if(!UserStateManager.isAdmin(req)){
            CommonUtil.sendJsonData(resp, null, 1, "无权操作！");
            return;
        }

        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String remarks = req.getParameter("remarks");

        //更新数据并向客户端返回消息
        try {
            if (mFoodTypeDao.updateFoodType(Integer.parseInt(id), name, remarks)) {
                CommonUtil.sendJsonData(resp, "更新成功", 0, "");
            } else {
                CommonUtil.sendJsonData(resp, "更新失败", 1, "");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, "更新失败", 1, exception.getMessage());
        }
    }

    public void getFoodType(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String id = req.getParameter("id");

        //更新数据并向客户端返回消息
        try {
            FoodType foodType = mFoodTypeDao.getFoodType(Integer.parseInt(id));
            if (foodType != null) {
                CommonUtil.sendJsonData(resp, foodType, 0, "");
            } else {
                CommonUtil.sendJsonData(resp, null, 1, "信息获取失败");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, null, 1, exception.getMessage());
        }
    }

    public void getAllFoodType(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //更新数据并向客户端返回消息
        try {
            List<FoodType> list = mFoodTypeDao.getAllFoodType();
            JSONArray jsonArray = JSONArray.fromObject(list);
            if (jsonArray != null) {
                CommonUtil.sendJsonData(resp, jsonArray, 0, "");
            } else {
                CommonUtil.sendJsonData(resp, null, 1, "信息获取失败");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, null, 1, exception.getMessage());
        }
    }

}
